/*****************************进度条与小球,以及歌词（由于时间相关，放一起了 ）*******************************/

function showCurrentTime() {
  const audio = document.getElementById("myAudio");
  const timeDisplay = document.getElementById("audio_time");
  const element = document.getElementById("ball");             //给小球加上drag检测
  const lyric_list = document.getElementById("container");
  const ul = document.getElementById("ul");
  element.addEventListener("dragstart", dragstart_handler);
  const liarr = lyric_list.getElementsByTagName("li");
  if (!audio || !timeDisplay) return;
  var offsetH=0;

  // 每次播放进度变化时更新显示
  audio.addEventListener('timeupdate', function () {
    // 格式化时间为 mm:ss
    const min = Math.floor(audio.currentTime / 60);
    const sec = Math.floor(audio.currentTime % 60).toString().padStart(2, '0');
    const du_min = Math.floor(audio.duration / 60);
    const du_sec = Math.floor(audio.duration % 60).toString().padStart(2, '0');;
    timeDisplay.textContent = `${min}:${sec}` + "/" + `${du_min}:${du_sec}`;
    document.getElementById("ball").style.left = 100 + "%";
    document.getElementById("progress-bar").style.width = audio.currentTime / audio.duration * 100 + "%";
    
    //歌词滚动
    var currentTime = audio.currentTime;
    for(var i=0;i<lyricTimeArr.length;i++){
      liarr[i].style.color="white";
      if(currentTime<lyricTimeArr[0]){          //    拖动到起点
        ul.style.transform = `translateY(-${0}vh)`;
      }
      if(currentTime>lyricTimeArr[lyricTimeArr.length-1]){         
        liarr[lyricTimeArr.length-1].style.color="green";
        var height=0;
        for(var j=0;j<i;j++)
          height+=liarr[j].offsetHeight;
        ul.style.transform = `translateY(-${height}px)`;
      }
      if((currentTime>=lyricTimeArr[i] && currentTime<lyricTimeArr[i+1]) )
      {
        liarr[i].style.color="green";
        var height=0;
        for(var j=0;j<i;j++)
          height+=liarr[j].offsetHeight;
        ul.style.transform = `translateY(-${height}px)`;
      }
    }
  });
}


function handle_lyric(lyricStr) {
  // 清空原有歌词
  var ul = document.getElementById("ul");
  ul.innerHTML = "";

  // 按行分割
  const lines = lyricStr.split('\n');
  // 存储每句歌词的起点时间（秒）
  const timeArr = [];
  const textArr = [];

  // 正则提取时间和歌词内容
  lines.forEach(line => {
    // 匹配如 [00:20.97] 的时间标签
    const match = line.match(/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/);
    // 去除时间标签后的歌词文本
    const text = line.replace(/\[\d{2}:\d{2}(?:\.\d{2,3})?\]/g, '').trim();
    if (match && text) {
      // 计算时间（秒）
      const min = parseInt(match[1]);
      const sec = parseInt(match[2]);
      const ms = match[3] ? parseInt(match[3].padEnd(3, '0')) : 0;
      const time = min * 60 + sec + ms / 1000;
      timeArr.push(time);
      textArr.push(text);

      var li = document.createElement("li");
      li.textContent = text;
      ul.appendChild(li);
    }
  });
  window.lyricTimeArr = timeArr;
  window.lyricTextArr = textArr;
}


function dragstart_handler(ev) {
  ev.dataTransfer.dropEffect = "move";
}

function enableProgressDrag() {
  const audio = document.getElementById("myAudio");
  const ball = document.getElementById("ball");
  const progressBar = document.getElementById("progress-bar");
  const progressContainer = document.getElementById("progress-container");

  let isDragging = false;

  ball.addEventListener('mousedown', function (e) {                  //按下鼠标
    isDragging = true;
    document.body.style.userSelect = "none"; // 防止选中文字
  });

  document.addEventListener('mousemove', function (e) {              //移动鼠标
    if (!isDragging) return;
    // 获取进度条容器的位置信息
    const rect = progressContainer.getBoundingClientRect();
    // 鼠标在进度条内的相对位置
    let offsetX = e.clientX - rect.left;
    offsetX = Math.max(0, Math.min(offsetX, rect.width)); // 限制在0~width之间
    // 计算百分比
    const percent = offsetX / rect.width;
    // 设置小球和进度条宽度
    ball.style.left = 100 + "%";
    progressBar.style.width = (percent * 100) + "%";
  });

  document.addEventListener('mouseup', function (e) {                //松开鼠标
    if (!isDragging) return;
    isDragging = false;
    document.body.style.userSelect = "";
    // 获取进度条容器的位置信息
    const rect = progressContainer.getBoundingClientRect();
    let offsetX = e.clientX - rect.left;
    offsetX = Math.max(0, Math.min(offsetX, rect.width));
    const percent = offsetX / rect.width;
    // 设置audio播放进度
    audio.currentTime = percent * audio.duration;
  });

  // 点击进度条也能跳转
  progressContainer.addEventListener('click', function (e) {
    const rect = progressContainer.getBoundingClientRect();
    let offsetX = e.clientX - rect.left;
    offsetX = Math.max(0, Math.min(offsetX, rect.width));
    const percent = offsetX / rect.width;
    audio.currentTime = percent * audio.duration;
  });
}

// 页面加载后调用
document.addEventListener("DOMContentLoaded", enableProgressDrag);